package servicios;

import java.io.IOException;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;

import businessLogic.model.AbstractModel;

import ApplicationLogic.controllers.CRUDController;

@Path("/crud")
public class CRUDServiceFacade extends AbstractService
{
	CRUDController CRUDControl = new CRUDController();
	AbstractModel Modelo;
	
	@POST
	@Produces(MediaType.TEXT_XML)
	@Consumes(MediaType.TEXT_XML)
	public String Alta(String ReceivedXML, @Context UriInfo alluri) throws Exception
	{
		
		//If we just receive the XML is a stand-alone entity, but if we receive parameters, it's a child entity.
		MultivaluedMap<String, String> mpAllQueryParams = alluri.getQueryParameters();
		//String Model = mpAllQueryParams.getFirst("model");
		String ParentModel = mpAllQueryParams.getFirst("ParentModel");
		String ParentChildAttribute = mpAllQueryParams.getFirst("ParentChildAttribute");
		String ParentModelID = mpAllQueryParams.getFirst("ParentModelID");

		mpAllQueryParams.remove("ParentModel");
		mpAllQueryParams.remove("ParentModelID");
		mpAllQueryParams.remove("ParentChildAttribute");
		
		try 
		{
			CRUDControl.Create(ReceivedXML);
		} 
		catch (Exception e) 
		{
			ReturnException(e.getMessage());
		}
		
	
	 return " ";
	}
	
	@DELETE
	@Produces(MediaType.TEXT_XML)
	@Consumes(MediaType.TEXT_XML)
	public String Baja(String XML)
	{
		try
		{
			CRUDControl.Delete(XML);
		}
		catch(Exception e)
		{
			ReturnException(e.getMessage());
		}
		 
	
	 return " ";
	}

	
	@PUT
	@Produces(MediaType.TEXT_XML)
	@Consumes(MediaType.TEXT_XML)
	public String Modificacion(String XML) throws SAXException, IOException, ParserConfigurationException, InstantiationException, IllegalAccessException, ClassNotFoundException
	{
		
		try 
		{
			CRUDControl.Update(XML);
		}
		catch (Exception e) 
		{
			ReturnException(e.getMessage());
		}
		
	
	 return " ";
	}
	
	@GET
	@Produces(MediaType.TEXT_XML)
	public String Listar(@QueryParam("model") String model,@QueryParam("Page") @DefaultValue("1") Integer Page) throws IllegalArgumentException, IllegalAccessException, InterruptedException
	{
		String XMLReturn = null;
		
		
		try
		{
			XMLReturn = CRUDControl.Read(model,Page);
		}
		catch(Exception e)
		{

			ReturnException(e.getMessage());
		}
		
		return XMLReturn;
	}


}
